package com.zgjkhis.logging.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.pagehelper.PageInfo;
import com.zgjkhis.common.service.impl.BaseServiceImpl;
import com.zgjkhis.common.utils.QueryHelpPlus;
import com.zgjkhis.domain.PageResult;
import com.zgjkhis.logging.aop.log.AppLog;
import com.zgjkhis.logging.aop.log.Log;
import com.zgjkhis.logging.domain.LogEntity;
import com.zgjkhis.logging.service.LogService;
import com.zgjkhis.logging.service.dto.LogErrorDTO;
import com.zgjkhis.logging.service.dto.LogQueryCriteria;
import com.zgjkhis.logging.service.dto.LogSmallDTO;
import com.zgjkhis.logging.service.mapper.LogMapper;
import com.zgjkhis.utils.*;
import org.apache.commons.codec.Charsets;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @date 2018-11-24
 */
@SuppressWarnings("unchecked")
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class LogServiceImpl extends BaseServiceImpl<LogMapper, LogEntity>  implements LogService {
    
    /**
     * 获取 request 请求内容
     *
     * @param request request
     * @return {String}
     */
    private static String getRequestContent(HttpServletRequest request) {
        try {
            String queryString = request.getQueryString();
            if (StringUtils.isNotBlank(queryString)) {
                return new String(queryString.getBytes(Charsets.ISO_8859_1), Charsets.UTF_8).replaceAll("&amp;", "&").replaceAll("%22", "\"");
            }
            String charEncoding = request.getCharacterEncoding();
            if (charEncoding == null) {
                charEncoding = StringPool.UTF_8;
            }
            byte[] buffer = getRequestBody(request.getInputStream()).getBytes();
            String str = new String(buffer, charEncoding).trim();
            if (StringUtils.isBlank(str)) {
                StringBuilder sb = new StringBuilder();
                Enumeration<String> parameterNames = request.getParameterNames();
                while (parameterNames.hasMoreElements()) {
                    String key = parameterNames.nextElement();
                    String value = request.getParameter(key);
                    StringUtils.appendBuilder(sb, key, "=", value, "&");
                }
                str = StringUtils.removeSuffix(sb.toString(), "&");
            }
            return str.replaceAll("&amp;", "&");
        } catch (Exception ex) {
            ex.printStackTrace();
            return StringPool.EMPTY;
        }
    }

    /**
     * 获取 request 请求体
     *
     * @param servletInputStream servletInputStream
     * @return body
     */
    private static String getRequestBody(ServletInputStream servletInputStream) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(servletInputStream, StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (servletInputStream != null) {
                try {
                    servletInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    @Override
    public PageResult<LogEntity> findAllByPageable(String nickname, Pageable pageable) {
        getPage(pageable);
        PageInfo<LogEntity> page = new PageInfo<>(baseMapper.findAllByPageable(nickname));
        return PageResult.data(page);
    }

    @Override
    public PageResult<LogEntity> queryAll(LogQueryCriteria criteria, Pageable pageable){
        getPage(pageable);
        PageInfo<LogEntity> page = new PageInfo<>(queryAll(criteria));
        return PageResult.data(page);
    }

    @Override
    public PageResult<LogErrorDTO> queryAllError(LogQueryCriteria criteria, Pageable pageable){
        getPage(pageable);
        PageInfo<LogEntity> page = new PageInfo<>(queryAll(criteria));
        return PageResult.data(page, LogErrorDTO.class);
    }

    @Override
    public List<LogEntity> queryAll(LogQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(LogEntity.class, criteria));
    }

    @Override
    public PageResult<LogSmallDTO> queryAllByUser(LogQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<LogEntity> page = new PageInfo<>(queryAll(criteria));
        return PageResult.data(page, LogSmallDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String username, String ip, ProceedingJoinPoint joinPoint,
                     LogEntity logEntity, Long uid){

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Log aopLog = method.getAnnotation(Log.class);

        // 方法路径
        String methodName = joinPoint.getTarget().getClass().getName()+"."+signature.getName()+"()";

        StringBuilder params = new StringBuilder("{");
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
                params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
            }
        }
        // 描述
        if (logEntity != null) {
            logEntity.setDescription(aopLog.value());
        }
        //类型 0-后台 1-前台
        logEntity.setType(aopLog.type());
        if(uid != null) {
            logEntity.setUid(uid);
        }
        assert logEntity != null;
        logEntity.setRequestIp(ip);

        String loginPath = "login";
        if(loginPath.equals(signature.getName())){
            try {
                assert argValues != null;
                username = new JSONObject(argValues[0]).get("username").toString();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        logEntity.setAddress(StringUtils.getCityInfo(logEntity.getRequestIp()));
        logEntity.setMethod(methodName);
        logEntity.setUsername(username);
        logEntity.setParams(params.toString() + " }");
        this.save(logEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveApp(String username, String ip, ProceedingJoinPoint joinPoint,
                        LogEntity logEntity, Long uid){

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AppLog aopLog = method.getAnnotation(AppLog.class);

        // 方法路径
        String methodName = joinPoint.getTarget().getClass().getName()+"."+signature.getName()+"()";

        StringBuilder params = new StringBuilder("{");
        //参数值
        Object[] argValues = joinPoint.getArgs();
        //参数名称
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        if(argValues != null){
            for (int i = 0; i < argValues.length; i++) {
                params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
            }
        }
        // 描述
        if (logEntity != null) {
            logEntity.setDescription(aopLog.value());
        }
        //类型 0-后台 1-前台
        logEntity.setType(aopLog.type());
        if(uid != null) {
            logEntity.setUid(uid);
        }
        assert logEntity != null;
        logEntity.setRequestIp(ip);

        String loginPath = "login";
        if(loginPath.equals(signature.getName())){
            try {
                assert argValues != null;
                username = new JSONObject(argValues[0]).get("username").toString();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        logEntity.setAddress(StringUtils.getCityInfo(logEntity.getRequestIp()));
        logEntity.setMethod(methodName);
        logEntity.setUsername(username);
        logEntity.setParams(params.toString() + " }");
        this.save(logEntity);
    }

    @Override
    public Object findByErrDetail(Long id) {
        LogEntity logEntity = this.getById(id);
        ValidationUtil.isNull( logEntity.getId(),"Log","id", id);
        byte[] details = logEntity.getExceptionDetail();
        return Dict.create().set("exception",new String(ObjectUtil.isNotNull(details) ? details : "".getBytes()));
    }

    @Override
    public void download(List<LogEntity> logEntities, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (LogEntity logEntity : logEntities) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户名", logEntity.getUsername());
            map.put("IP", logEntity.getRequestIp());
            map.put("IP来源", logEntity.getAddress());
            map.put("描述", logEntity.getDescription());
            map.put("浏览器", logEntity.getBrowser());
            map.put("请求耗时/毫秒", logEntity.getTime());
            map.put("异常详情", new String(ObjectUtil.isNotNull(logEntity.getExceptionDetail()) ? logEntity.getExceptionDetail() : "".getBytes()));
            map.put("创建日期", logEntity.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delAllByError() {
        baseMapper.deleteByLogType("ERROR");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delAllByInfo() {
        baseMapper.deleteByLogType("INFO");
    }

    @Override
    public void saveError(Throwable error, HttpServletRequest request, String username, Long uid, Integer type) {
        LogEntity logEntity = new LogEntity();
        logEntity.setLogType("ERROR");

        if (Func.isNotEmpty(error)) {
            logEntity.setExceptionDetail(ThrowableUtil.getStackTrace(error).getBytes());
            logEntity.setRequestIp(StringUtils.getIp(request));
            logEntity.setAddress(StringUtils.getCityInfo(logEntity.getRequestIp()));
            StackTraceElement[] elements = error.getStackTrace();
            if (Func.isNotEmpty(elements)) {
                StackTraceElement element = elements[0];
                logEntity.setMethod(element.getClassName() + "." + element.getMethodName() + "()");
            }
        }
        logEntity.setDescription(request.getRequestURI());
        logEntity.setUid(uid);
        logEntity.setType(type);
        logEntity.setUsername(username);
        logEntity.setTime(0L);
        logEntity.setParams(getRequestContent(request));
        baseMapper.insert(logEntity);
    }
}
